package com.example.xm.controller;

import com.example.xm.entity.*;
import com.example.xm.mapper.DingcaiMapper;
import com.example.xm.mapper.FenleiMapper;
import com.example.xm.service.TieziService;
import com.example.xm.web.Result;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/tiezi")
public class TieziController {
    @Autowired
    TieziService tieziService;
    @Autowired
    FenleiMapper fenleiMapper;
    @Autowired
    DingcaiMapper dingcaiMapper;
    @PostMapping("/add")
    public Result reg(@RequestBody Tiezi tiezi){
        String cname = fenleiMapper.selectNameById(tiezi.getCid());
        tiezi.setTime(new Date());
        tiezi.setLiulan(0);
        tiezi.setDing(0);
        tiezi.setCname(cname);
        tiezi.setCai(0);
        tiezi.setStatus(1);
        tieziService.save(tiezi);
        String furl = tiezi.getFurl();
        return Result.success();
    }
    @GetMapping("/list")
    public Result list(Integer page,Integer size,Integer uid,Integer cid,Integer status){
        PageInfo<Tiezi> pageInfo= tieziService.list(page,size,uid,cid,status);
        return Result.success(pageInfo);
    }
    @PostMapping("/update")
    public Result update(@RequestBody Tiezi tiezi){
        tieziService.updateById(tiezi);
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result get(@PathVariable Integer id,Integer uid){
        Tiezi byId = tieziService.getById(id);
        TieziVO tieziVO = new TieziVO();
        BeanUtils.copyProperties(byId,tieziVO);
        //修改浏览量
        byId.setLiulan(byId.getLiulan()+1);
        tieziService.updateById(byId);
        //设置顶踩状态
        List<DingCai> list1 = dingcaiMapper.selectList(uid, null, 1,id);
        if(list1!=null&&list1.size()>0){
            tieziVO.setIsDing(true);
        }
        List<DingCai> list2 = dingcaiMapper.selectList(uid, null, 2,id);
        if(list2!=null&&list2.size()>0){
            tieziVO.setIsCai(true);
        }
        return Result.success(tieziVO);
    }
    @GetMapping("/delete/{ids}")
    public Result delete(@PathVariable String ids){
        String[] split = ids.split(",");
        int[] intArray = new int[split.length];
        for (int i = 0; i < split.length; i++) {
            intArray[i] = Integer.parseInt(split[i]);
        }
        tieziService.delete(intArray);
        return Result.success();
    }
}
